package com.xcc.annotation.ioc;

import com.xcc.annotation.ioc.bean.Car;
import com.xcc.annotation.ioc.config.*;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class MainTest {

    /**
     * 测试包扫描
     */
    @Test
    public void testComponentScan() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo01_ComponentScan.class);
        String[] names = applicationContext.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

    /**
     * 测试import
     */
    @Test
    public void testImport() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo02_Import.class);
        String[] names = applicationContext.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

    /**
     * 测试FactoryBean
     */
    @Test
    public void testFactoryBean() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo03_FactoryBean.class);
        //注入的方法名
        Object o1 = applicationContext.getBean("myFactoryBean");
        Object o2 = applicationContext.getBean("myFactoryBean");
        Object o3 = applicationContext.getBean("&myFactoryBean");
        System.out.println(o1);
        System.out.println(o1 == o2);
        System.out.println("&获取的对象为: "+ o3);
    }


    /**
     * 测试bean生命周期
     */
    @Test
    public void testBeanLifeCycle() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo04_BeanLifeCycle.class);
        //注入的方法名
        Object o1 = applicationContext.getBean("car");
//        System.out.println(o1);
        applicationContext.close();
    }

    /**
     * 测试Profile
     */
    @Test
    public void testProfile() throws SQLException {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //1、创建一个applicationContext
        //2、设置需要激活的环境
        applicationContext.getEnvironment().setActiveProfiles("dev");
        //3、注册主配置类
        applicationContext.register(Demo05_ProfileAndPropertySource.class);
        //4、启动刷新容器
        applicationContext.refresh();
        //注入的方法名
        String[] names = applicationContext.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

}
